﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Hr;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.UICommon;
using ESOL.WinUI.Hr;

namespace ESOL.WinUI.Finance
{
    public partial class frmMaintainMonthSalary : BaseForm.frmBaseDialogyBusinessForm
    {
        #region Variable
        private string mSalaryMonth;
        private MstPersonEntity mSelectedPerson;
        private HrMonthSalaryEntity mSelectedMonthSalary;
        private List<HrMonthSalaryItemEntity> DeleteList = new List<HrMonthSalaryItemEntity>();
        #endregion

        #region Constructor
        public frmMaintainMonthSalary(string salaryMonth, MstPersonEntity person, HrMonthSalaryEntity monthSalary)
        {
            InitializeComponent();
            mSalaryMonth = salaryMonth;
            mSelectedPerson = person;
            mSelectedMonthSalary = monthSalary;
            if (mSelectedMonthSalary == null)
            {
                mSelectedMonthSalary = new HrMonthSalaryEntity();
                mSelectedMonthSalary.MonthSalaryId = Guid.NewGuid().ToString();
                mSelectedMonthSalary.PersonId = person.PersonId;
            }
        }
        #endregion

        #region Functions
        private void InitBasicSalary()
        {
            if (gvDetail.DataSource == null)
            {
                BindDataGridDetail();
            }
            if (mSelectedPerson == null)
            {
                return;
            }
            HrEmployeeEntity employee = HrEmployeeBs.GetHrEmployeeByPersonId(mSelectedPerson.PersonId);
            if (employee == null)
            {
                return;
            }
            DataTable dt = (DataTable)gvDetail.DataSource;
            if (employee.BasicSalary > 0)
            {
                DataRow dr = dt.NewRow();
                dr["ITEM_ID"] = Guid.NewGuid().ToString();
                dr["MONTH_SALARY_ID"] = mSelectedMonthSalary.MonthSalaryId;
                dr["SALARY_ITEM"] = "SI01";
                dr["SALARY"] = employee.BasicSalary;
                dt.Rows.Add(dr);
            }
            if (employee.SocialFundAmount > 0)
            {
                DataRow dr = dt.NewRow();
                dr["ITEM_ID"] = Guid.NewGuid().ToString();
                dr["MONTH_SALARY_ID"] = mSelectedMonthSalary.MonthSalaryId;
                dr["SALARY_ITEM"] = "SI08";
                dr["SALARY"] = -employee.SocialFundAmount;
                dt.Rows.Add(dr);
            }
            ResetTotalAmount();
        }
        private void SetPersonFields()
        {
            if (mSelectedPerson == null)
            {
                return;
            }
            txtPersonCode.Text = mSelectedPerson.PersonCode;
            txtPersonNameCn.Text = mSelectedPerson.NameCn;
            cmbStatus.SetSelectedValue(mSelectedPerson.Status);
            txtMobile.Text = mSelectedPerson.Mobile;
            MstPositionEntity position = MstPositionBs.GetMstPositionByID(mSelectedPerson.PositionId);
            if (position != null)
            {
                txtPosition.Text = position.PositionName;
            }
            HrEmployeeEntity employee = HrEmployeeBs.GetHrEmployeeByPersonId(mSelectedPerson.PersonId);
            if (employee != null)
            {
                txtIdNo.Text = employee.IdNo;
                txtBasicSalary.Text = employee.BasicSalary.ToString("#0.00");
            }
        }
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbSalaryStatus, "MSS", false);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "PS", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSALARY_ITEM, "SI", false);
        }
        private void SetFields()
        {
            SetPersonFields();
            if (mSelectedMonthSalary == null)
            {
                BindDataGridDetail();
                return;
            }
            txtSalaryMonth.Text = mSalaryMonth;
            cmbSalaryStatus.SetSelectedValue(mSelectedMonthSalary.Status);
            txtRemark.Text = mSelectedMonthSalary.Remark;

            UICommonFunctions.SetTextBoxDate(txtCreatedDate, mSelectedMonthSalary.CreatedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, mSelectedMonthSalary.CreatedBy);
            UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, mSelectedMonthSalary.LastModifiedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, mSelectedMonthSalary.LastModifiedBy);
            UICommonFunctions.SetTextBoxDate(txtApprovedDate, mSelectedMonthSalary.ApprovedDate, "yyyy-MM-dd hh:mm:ss");
            UICommonFunctions.SetTextBoxPersonName(txtApprovedBy, mSelectedMonthSalary.ApprovedBy);

            BindDataGridDetail();
        }
        private void BindDataGridDetail()
        {
            string monthSalaryId = "";
            if (mSelectedMonthSalary != null)
            {
                monthSalaryId = mSelectedMonthSalary.MonthSalaryId;
            }
            DataSet ds = HrMonthSalaryItemBs.GetHrMonthSalaryItemDataSet(monthSalaryId);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
                return;
            }
            DataTable dt = ds.Tables[0];
            dt.AcceptChanges();
            gvDetail.DataSource = dt;
            DeleteList = new List<HrMonthSalaryItemEntity>();
            ResetTotalAmount();
        }
        private void BindLeaveInfoGrid()
        {
            if (mSelectedPerson == null || string.IsNullOrEmpty(mSalaryMonth))
            {
                return;
            }
            DataSet ds = HrLeaveApplicationBs.GetLeaveApplicationForSalary(mSalaryMonth, mSelectedPerson.PersonId);
            if (ds != null && ds.Tables.Count > 0)
            {
                gvLeaveInfo.DataSource = ds.Tables[0];
            }
            else
            {
                gvLeaveInfo.DataSource = null;
            }
        }
        private void BindTravelInfoGrid()
        {
            if (mSelectedPerson == null || string.IsNullOrEmpty(mSalaryMonth))
            {
                return;
            }
            DataSet ds = HrTravelApplicationBs.GetTravelApplicationForSalary(mSalaryMonth, mSelectedPerson.PersonId);
            if (ds != null && ds.Tables.Count > 0)
            {
                gvTravelInfo.DataSource = ds.Tables[0];
            }
            else
            {
                gvTravelInfo.DataSource = null;
            }
        }
        private void BindAttendanceInfoGrid()
        {
            if (mSelectedPerson == null || string.IsNullOrEmpty(mSalaryMonth))
            {
                return;
            }
            string condition = " AND P.PERSON_ID = '" + mSelectedPerson.PersonId + "'";
            condition += " AND AR.ATTENDANCE_DATE LIKE '%" + mSalaryMonth.Substring(0, 4) + "-" + mSalaryMonth.Substring(4) + "%'";
            DataTable dt = HrAttendanceRecordBs.GetDetailByCondition(condition, "AR.ATTENDANCE_DATE");
            gvAttendanceInfo.DataSource = dt;
        }

        private void SetEntity()
        {
            mSelectedMonthSalary.SalaryMonth = mSalaryMonth;
            mSelectedMonthSalary.Status = "MSS02";
            mSelectedMonthSalary.TotalSalary = CommonFunctions.ToDecimal(txtTotalSalary.Text);
            mSelectedMonthSalary.Remark = txtRemark.Text; 
            
            if (ThisActionType == ActionType.New)
            {
                mSelectedMonthSalary.CreatedDate = DateTime.Now;
                mSelectedMonthSalary.CreatedBy = CommonParameter.CurrentUser.PersonId;
            }
            if (ThisActionType == ActionType.New || ThisActionType == ActionType.Modify)
            {
                mSelectedMonthSalary.LastModifiedDate = DateTime.Now;
                mSelectedMonthSalary.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
            }
        }
        private void ResetTotalAmount()
        {
            decimal totalAmount = 0;
            DataTable dt = gvDetail.DataSource as DataTable;
            foreach(DataRow dr in dt.Rows)
            {
                if (string.IsNullOrEmpty(dr["SALARY"].ToString()) == false)
                {
                    decimal salary = CommonFunctions.ToDecimal(dr["SALARY"].ToString());
                    totalAmount += salary;
                }
            }
            txtTotalSalary.Text = decimal.Round(totalAmount, 2).ToString();
        }
        private bool CheckData()
        {
            DataTable dt = gvDetail.DataSource as DataTable;
            if (dt == null || dt.Rows.Count == 0)
            {
                MessageBox.Show("工资明细不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["SALARY_ITEM"] == null || dt.Rows[i]["SALARY_ITEM"].ToString() == "")
                {
                    MessageBox.Show("工资项目不能为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return false;
                }
            }
            return true;
        }
        private bool Save()
        {
            try
            {
                if (CheckData() == false)
                {
                    return false;
                }
                if (ThisActionType == ActionType.New)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = HrMonthSalaryBs.SaveMonthSalary(true, mSelectedMonthSalary, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("新增失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Modify)
                {
                    SetEntity();
                    DataTable dt = (DataTable)gvDetail.DataSource;
                    bool isSuccessful = HrMonthSalaryBs.SaveMonthSalary(false, mSelectedMonthSalary, dt, DeleteList);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("修改失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                else if (ThisActionType == ActionType.Approve)
                {
                    mSelectedMonthSalary.ApprovedDate = DateTime.Now;
                    mSelectedMonthSalary.ApprovedBy = CommonParameter.CurrentUser.PersonId;
                    bool isSuccessful = HrMonthSalaryBs.UpdateHrMonthSalary(mSelectedMonthSalary);
                    if (!isSuccessful)
                    {
                        MessageBox.Show("审核失败！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            BindComboBox();
            SetFields();
            if (ThisActionType == ActionType.New)
            {
                InitBasicSalary();
            }
            BindLeaveInfoGrid();
            BindTravelInfoGrid();
            BindAttendanceInfoGrid();
        }
        DataRow drSelected;
        private void gridView4_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected = gridView4.GetDataRow(e.FocusedRowHandle);
        }

        private void tsmNewLine_Click(object sender, EventArgs e)
        {
            DataTable dt = gvDetail.DataSource as DataTable;
            DataRow dr = dt.NewRow();
            dr["ITEM_ID"] = Guid.NewGuid().ToString();
            dr["MONTH_SALARY_ID"] = mSelectedMonthSalary.MonthSalaryId;
            dt.Rows.Add(dr);
        }

        private void tsmDelLine_Click(object sender, EventArgs e)
        {
            if (drSelected == null)
            {
                return;
            }
            if (drSelected.RowState != DataRowState.Added)
            {
                HrMonthSalaryItemEntity entity = new HrMonthSalaryItemEntity(drSelected);
                DeleteList.Add(entity);
            }
            DataTable dt = gvDetail.DataSource as DataTable;
            dt.Rows.Remove(drSelected);
            ResetTotalAmount();
        }

        private void gridView4_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("SALARY"))
            {
                ResetTotalAmount();
            }
        }

        DataRow drSelected2;
        private void gridView2_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected2 = gridView2.GetDataRow(e.FocusedRowHandle);
        }

        private void repositoryItemButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            HrTravelApplicationEntity entity = new HrTravelApplicationEntity(drSelected2);
            frmMaintainTravelApplication frm = new frmMaintainTravelApplication(entity);
            frm.ThisActionType = ActionType.View;
            frm.ShowDialog();
        }

        DataRow drSelected3;
        private void gridView3_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            drSelected3 = gridView3.GetDataRow(e.FocusedRowHandle);
        }

        private void repositoryItemButtonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            HrLeaveApplicationEntity entity = new HrLeaveApplicationEntity(drSelected3);
            frmMaintainLeaveApplication frm = new frmMaintainLeaveApplication(entity);
            frm.ThisActionType = ActionType.View;
            frm.ShowDialog();
        }

        protected override void Click_Save()
        {
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Approve()
        {
            if (mSelectedMonthSalary == null)
            {
                return;
            }
            mSelectedMonthSalary.Status = "MSS03";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        protected override void Click_Reject()
        {
            if (mSelectedMonthSalary == null)
            {
                return;
            }
            mSelectedMonthSalary.Status = "MSS04";
            if (Save())
            {
                this.DialogResult = DialogResult.OK;
            }
        }
        #endregion
    }
}
